<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="30%"
    append-to-body
    @open="dialogOpen"
    @close="dialogClose"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select
          v-model="form.category"
          placeholder="请选择类别"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="category in categorys"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件">
        <el-upload
          ref="upload"
          name="file"
          :before-upload="beforeUpload"
          :multiple="false"
          :accept="fileAccept"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-change="fileChange"
          :on-remove="fileRemove"
          :http-request="uploadHandler"
          :limit="1"
          :action="uploadUrl"
          :on-exceed="fileExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">添加文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入说明" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addOrUpdate } from '@/api/baseManage/knowledgeBase'
import { getToken } from '@/utils/auth'
export default {
  name: 'AddOrUpdateDialog',
  props: {
    title: { type: String, default: '' },
    show: { type: Boolean, default: false },
    data: { type: Object, default: () => {} }
  },
  data() {
    return {
      visible: false,
      fileTypes: ['doc', 'xls', 'docx', 'pdf', 'xlsx'],
      fileAccept: '.doc, .xls, .docx, .pdf, .xlsx',
      loading: false,
      form: {
        id: '',
        name: '',
        category: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        category: [
          { required: false, message: '类别不能为空', trigger: 'blur' }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/gcxt/knowledgeBase/add',
      headers: { Authorization: 'Bearer ' + getToken() },
      categorys: [],
      fileList: [],
      selectFile: undefined
    }
  },
  watch: {
    show(val) {
      this.visible = val
    }
  },
  methods: {
    /**
     * 文档上传前置事件
     * @param file 文件
     */
    beforeUpload(file) {
      // console.log('上传图片：', file)
      // const filename = file.name
      // if(this.fileTypes.includes(filename)) {
      //
      // }
      // if (!this.dialogMetadata.form.name) {
      //   this.dialogMetadata.form.name = filename
      // }
    },
    /**
     * 文件上传成功
     * @param res
     * @param file
     * @param fileList
     */
    handleUploadSuccess(res, file, fileList) {
      this.loading = false
      if (res.code === 200) {
        this.$message.success('添加成功')
        this.$emit('change', this.form)
        this.$emit('update:show', false)
      } else {
        this.$message.error('添加失败')
      }
    },
    /**
     * 文件上传失败
     * @param err
     * @param file
     * @param fileList
     */
    // eslint-disable-next-line handle-callback-err
    handleUploadError(err, file, fileList) {
      this.loading = false
      this.$message.error('添加失败')
    },
    /**
     * 文件改变
     * @param file
     */
    fileChange(file) {
      const filename = file.name
      const name = filename.substring(0, filename.lastIndexOf('.'))
      const type = filename.substring(filename.lastIndexOf('.') + 1)
      if (!this.fileTypes.includes(type)) {
        this.$message.warning('文件格式不支持')
        this.$refs.upload.clearFiles()
      }
      if (file.status === 'ready' && !this.form.name) {
        this.form.name = name
        this.$refs.form.clearValidate('name')
      }
    },
    /**
     * 文件超出数量限制
     * @param files
     * @param fileList
     */
    fileExceed(files, fileList) {
      this.$message.warning('文件已存在')
    },
    /**
     * 文件移除
     * @param file
     * @param fileList
     */
    fileRemove(file, fileList) {
      const filename = file.name.substring(0, file.name.lastIndexOf('.'))
      if (this.form.name === filename) {
        this.form.name = ''
      }
    },
    /**
     * 自定义上传
     * @param data
     */
    uploadHandler(data) {
      this.selectFile = data.file
    },
    /**
     * 窗口打开
     */
    dialogOpen() {
      const data = this.data
      if (data.id) {
        this.form = Object.assign(this.form, {
          id: data.id,
          name: data.name,
          category: data.category,
          description: data.description
        })
        this.fileList = [{ url: process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + data.fileId, name: data.fileName }]
      }
    },
    /**
     * 窗口关闭处理
     */
    dialogClose() {
      this.form.id = ''
      this.form.name = ''
      this.form.category = ''
      this.form.description = ''
      this.selectFile = undefined
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      this.$emit('update:show', false)
    },
    /**
     * 取消
     */
    cancel() {
      this.show = false
    },
    /**
     * 确认
     */
    confirm() {
      this.loading = true
      const data = this.form
      const form = new FormData()
      if (this.selectFile) {
        form.append('file', this.selectFile)
      }
      const id = data.id
      form.append('id', id)
      form.append('name', data.name)
      form.append('category', data.category)
      form.append('description', data.description)

      addOrUpdate(form).then(res => {
        if (res.code === 200) {
          this.selectFile = undefined
          this.$message.success(`${id ? '新增' : '修改'}成功`)
          this.$emit('change', data)
          this.$emit('update:show', false)
        } else {
          this.$message.error(`${id ? '新增' : '修改'}失败`)
        }
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style scoped>

</style>
